package org.jflame.devAide.plugin;

import org.jflame.commons.codec.TranscodeHelper;
import org.jflame.commons.util.StringHelper;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;

public class EncodeController {

    @FXML
    private Button btnEncode;
    @FXML
    private Button btnDencode;
    @FXML
    private ComboBox<String> cbxEncodeType;
    @FXML
    private TextArea txaUnencode;
    @FXML
    private TextArea txaEncoded;
    @FXML
    private CheckBox chxUrlSafe;

    private final String[] encodeTypes = { "Base64","图片转Base64","URL编码","中文转UNICODE" };

    public EncodeController() {
        cbxEncodeType.setItems(FXCollections.observableArrayList(encodeTypes));
        cbxEncodeType.getSelectionModel()
                .selectedItemProperty()
                .addListener(new ChangeListener<String>() {

                    @Override
                    public void changed(ObservableValue<? extends String> observable, String oldValue,
                            String newValue) {
                        if (encodeTypes[0].equals(newValue)) {
                            chxUrlSafe.setVisible(true);
                            if (!txaEncoded.isEditable()) {
                                txaEncoded.setEditable(false);
                            }
                        } else if (encodeTypes[1].equals(newValue)) {
                            chxUrlSafe.setVisible(true);
                            txaEncoded.setEditable(false);
                            txaEncoded.setText("拖拽图片到此");
                        }
                    }
                });
        txaEncoded.setOnDragOver(null);
    }

    @FXML
    private void handleEncode(ActionEvent event) {
        String srcText = txaEncoded.getText();
        if (StringHelper.isEmpty(srcText)) {
            return;
        }

        String type = cbxEncodeType.getValue();
        if (StringHelper.isEmpty(type)) {
            return;
        }
        String resultText;
        if (encodeTypes[0].equals(type)) {
            boolean isSafeUrl = chxUrlSafe.isSelected();
            if (isSafeUrl) {
                resultText = TranscodeHelper.encodeBase64URLSafeString(srcText);
            } else {
                resultText = TranscodeHelper.encodeBase64String(srcText);
            }
        } else if (encodeTypes[1].equals(type)) {
            resultText = TranscodeHelper.encodeBase64String(srcText);
        }
    }

    @FXML
    private void handleDencode(ActionEvent event) {

    }

    private class EncodeFactory {

    }
}
